<?php

namespace CSan\NutrientBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use CSan\NutrientBundle\Entity\Food;

/**
 * @Route("/nutrient/food")
 */
class FoodController extends Controller
{
    /**
     * @Route("/",
     *      name = "csan_nutrient_food_index",
     * 	    requirements = {
     * 	        "_method" = "GET"
     * 	    }
     * ),
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/search.{_format}",
     *      name = "csan_nutrient_food_search",
     * 	    requirements = {
     * 	        "_method" = "GET",
     *          "_format" = "json"
     * 	    }
     * ),
     * @Template("CSanNutrientBundle:Food:search.json.twig")
     */
    public function searchAction($_format)
    {
        $params = $this->bindQuery();
        $foods = $this->getDoctrine()->getEntityManager()->getRepository('CSanNutrientBundle:Food')->findAll($params);

        return array(
            'foods' => $foods,
        );
    }

    /**
     * @Route("/read/{publicId}.{_format}",
     * 	    name = "csan_nutrient_food_read",
     * 	    requirements = {
     *          "_method" = "GET",
     *          "publicId" = "[a-zA-Z0-9]{6,32}",
     *          "_format" = "json"
     * 	    }
     * ),
     * @Template()
     */
    public function readAction($publicId, $_format)
    {	
        $food = $this->getDoctrine()->getEntityManager()->getRepository('CSanNutrientBundle:Food')->findOne(array('publicId' => $publicId));

        return array(
            'food' => $food,
        );
    }

    public function bindQuery(array $params = array())
    {
        $query = $this->get('request')->query;

        $extraParams = array(
            'name' => $query->get('name'),
            'limit' => 100,
        );

        return array_merge($params, $extraParams);
    }
}